<template>
<!--  <div>{{ store.count }}</div>-->
<!--  <button @click="changeCount">点击加一</button>-->
<!--&lt;!&ndash;  <div>{{ changCount }}</div>&ndash;&gt;-->
<!--  <el-button type="primary" @click="edit">Primary</el-button>-->
  <div class="LogIn">
    <!--    <img src="../assets/image/lonInBgc.png" alt="">-->
    <div class="main">
      <div class="Controls">
        <h2 class="welcome">WELCOME</h2>
        <h3 class="title">欢迎登录后台管理系统</h3>
        <el-form
            v-if="flag"
            ref="formRef"
            :model="numberValidateForm"
            label-width="100px"
            class="demo-ruleForm"
            :rules="rulesLog"
        >
          <el-form-item
              label="账号"
              prop="account"
          >
            <el-input
                v-model.trim="numberValidateForm.account"
                type="text"
                autocomplete="off"
            />
          </el-form-item>
          <el-form-item
              label="密码"
              prop="password"
          >
            <el-input
                v-model.trim="numberValidateForm.password"
                type="password"
                autocomplete="off"
                show-password
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(formRef)">登录</el-button>
            <el-button @click="resetForm(formRef)">清空</el-button>
            <el-button type="danger" link @click="SignIn">注册账号</el-button>
          </el-form-item>
        </el-form>
        <el-form
            v-else
            ref="ruleFormRef"
            :model="ruleForm"
            status-icon
            :rules="rules"
            label-width="120px"
            class="demo-ruleForm"
        >
          <el-form-item label="注册名" prop="age">
            <el-input v-model.number="ruleForm.age" />
          </el-form-item>
          <el-form-item label="输入密码" prop="pass">
            <el-input v-model="ruleForm.pass" show-password type="password" autocomplete="off" />
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input
                v-model="ruleForm.checkPass"
                type="password"
                show-password
                autocomplete="off"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitFormX(ruleFormRef)"
            >注册</el-button
            >
            <el-button @click="resetFormX(ruleFormRef)">重置</el-button>
            <el-button link type="danger" @click="flag=true">返回登入页面</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
<!--  <el-button :plain="true">Show message</el-button>-->
</template>

<script setup lang="ts">

// // 可以监听数据变化并且跟踪到
// import {storeToRefs} from "pinia";
import useStore from '../modules/store/proList.ts'
import useStoreOne from '../modules/store/Authority'
// // 可以解构赋值直接使用至页面中，
// const {count} = storeToRefs(store)
// console.log(store)
// const changeCount = ()=>{
//   // 可以通过改写上面赋值出来的count.value方法来进行一个更改数据并且响应式
//   // count.value++
//   // 批量更改的方法$patch
//   store.$patch({
//     count: store.count + 1
//   })
// }
// const edit = ()=>{
//   // 直接通过store调用upCount方法
//   store.upCount(5)
// }

import { reactive, ref } from 'vue'
import { ElMessage,ElLoading } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
// import { ElLoading } from 'element-plus'
// import {  } from 'element-plus'
// import type { FormInstance, FormRules } from 'element-plus'
import router from "../modules/router";
const checkAge = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入账户.'))
  }
    // 2-6位的名字
    const regExp =/^[\u4e00-\u9fa5a-zA-Z0-9]{2,6}$/
    if (!regExp.test(value)) {
      callback(new Error('请输入2-6位的名字'))
    } else {
      callback()
    }
    callback()
}

// 输入密码l
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('密码没有值'))
  } else {
    // setTimeout(() => {
      // 至少8个字符，至少1个大写字母，1个小写字母和1个数字,不能包含特殊字符（非数字字母）
      const regExp =/^(?=.*[A-Za-z ])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$/
      if (!regExp.test(value)) {
        callback(new Error('需要8-16位数值,大小写至少一个'))
      } else {
        callback()
      }
      callback()
    // }, 1000);
  }
}
// 再次确认密码
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('Please input the password again'))
  } else if (value !== ruleForm.pass) {
    callback(new Error("Two inputs don't match!"))
  } else {
    callback()
  }
}
const formRef = ref<FormInstance>()
// const ruleFormRef = ref<FormInstance>()

// 监听到数据库
const store = useStore()
const storeA = useStoreOne()
const numberValidateForm = reactive({
  account: '',
  password: ''
})

// 登录注册的切换
const flag = ref(true)
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid: boolean) => {
    if (valid) {
        // store.loading()
        // setTimeout(() => {
      let num:number = 0
            storeA.list.some((item:any)=>{
              if (numberValidateForm.account === item.AccountNumber && numberValidateForm.password === item.password) {
                num++
                localStorage.setItem('token',numberValidateForm.account)
                console.log('Received values of form: ', numberValidateForm)
                router.push({
                  path: '/Main/Home'
                })
                // 消息提示框
                ElMessage({
                  message: '登录成功,尽情浏览吧.',
                  grouping: true,
                  type: 'success',
                })
                return true
              }
            })
      if(num===0){
        ElMessage({
          message: '账号密码错误',
          type:'error'
        })
      }
        // }, 1000)
    } else {
      console.log('error submit!')
      return false
    }
  })
}
// 重置按钮
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
// 点击注册切换至注册表单
const SignIn = ()=>{
  flag.value = false
}







// 注册逻辑
const ruleFormRef = ref<FormInstance>()
// 注册名字的验证

// 表单验证的数据
const ruleForm = reactive({
  pass: '',
  checkPass: '',
  age: '',
})
// rules表单校验
const rules = reactive<FormRules<typeof ruleForm>>({
  pass: [{ validator: validatePass, trigger: 'blur' }],
  checkPass: [{ validator: validatePass2, trigger: 'blur' }],
  age: [{ validator: checkAge, trigger: 'blur' }],
})
// rules表单校验
const rulesLog = reactive<FormRules<typeof numberValidateForm>>({
  account: [{ validator: checkAge, trigger: 'blur' }],
  password: [{ validator: validatePass, trigger: 'blur' }],
  // age: [{ validator: checkAge, trigger: 'blur' }],
})
const submitFormX = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid:any) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      setTimeout(() => {
        const obj = {
          AccountNumber: ruleForm.age,
          password: ruleForm.checkPass
        }
        storeA.add(obj)
        loading.close()
        ElMessage({
          message: '注册成功，请登录',
          type: 'success',
        })
        flag.value = true
      }, 1000)
      console.log('submit!')
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetFormX = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped lang="scss">
.LogIn {
  height: 100vh;
  width: 100vw;
  //background: pink;
  background-image: url('../../public/img/lonInBgc.png');
  background-size: 100% 100%;

  .main {
    position: absolute;
    top: 50%;
    left: 50%;
    height: 700px;
    width: 1200px;
    //margin: 0 auto;
    margin-left: -600px;
    margin-top: -350px;
    background-image: url('../../public/img/logInMain.gif');
    background-size: 100% 100%;
    //transform: translate(-10px, -10px);
    .Controls {
      margin-top: 52px;
      margin-left: 71px;
      padding: 56px 71px;
      box-sizing: border-box;
      width: 501px;
      height: 595px;
      background-color: #ffffff;
      box-shadow: 7px 11px 37px 1px rgba(0, 123, 237, 0.4);
      border-radius: 10px;

      .welcome {
        width: 216px;
        height: 31px;
        font-family: TsangerXWZ;
        font-size: 42px;
        font-weight: 600;
        font-stretch: normal;
        margin-bottom: 20px;
        line-height: 50px;
        letter-spacing: 0px;
        color: #d83030;
      }

      .title {
        font-family: SourceHanSansCN-Bold;
        font-size: 28px;
        font-weight: 600;
        font-stretch: normal;
        line-height: 40px;
        margin-bottom: 60px;
        color: #808080;
      }
    }
  }
}

</style>
